package com.yingpai.fitness.dvp_2_0.main.activity.fitness;

import android.Manifest;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.lzy.okgo.model.Response;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.store.StoreListBean;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;

import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Comparator;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Created by ASUS on 2018/8/13.
 */

public class StoreActivity extends CommonActivity implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.listview)
    XListView listview;
    @BindView(R.id.swiperefresh)
    SwipeRefreshLayout swiperefresh;
    private QuickAdapter<StoreListBean.MapData.StoreListData> quickAdapter;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private double latitude;
    private double longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.activity_store);
    }

    @Override
    protected void initView() {
        setTitle("门店选择");

        swiperefresh.setOnRefreshListener(this);

        quickAdapter = new QuickAdapter<StoreListBean.MapData.StoreListData>(this, R.layout.item_store) {
            @Override
            protected void convert(BaseAdapterHelper helper, StoreListBean.MapData.StoreListData item) {
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhotoUrls().substring(0, item.getPhotoUrls().indexOf(",")))
                        .error(R.mipmap.default_big_bg)
                        .into(photo);

                helper.setText(R.id.name, item.getStoreName());

                helper.setText(R.id.address, item.getAddress());

                helper.setText(R.id.distance, item.getDistance() + "km");

            }
        };

        listview.setAdapter(quickAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putInt("id", quickAdapter.getItem(position).getId());
                startActivity(StoreDetailActivity.class,bundle);
            }
        });
    }

    @Override
    protected void initData() {
        if (!rxPermissions.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)) {
            rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean) {
                        initLocation();
                        mLocationClient.start();//重新定位
                    } else {
                        showToast("拒绝权限可能导致部分功能不能使用");
                    }
                }
            });
        } else {
            initLocation();
            mLocationClient.start();//重新定位
        }
    }

    private void initLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(0);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
    }

    @Override
    public void onRefresh() {
        mLocationClient.start();
    }

    @Override
    @OnClick({})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
        }
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //获取纬度信息
            latitude = location.getLatitude();
            //获取经度信息
            longitude = location.getLongitude();
            showDialog(context,null);
            finalOkGo.request(RequestType.GET, Contacts.HOST_SERVER + Url.GET_STORE_LIST, null, Url.GET_STORE_LIST, new Callback<StoreListBean>() {
                @Override
                public void onSuccess(StoreListBean storeListBean) {
                    if (Constant.REQUEST_SUCCESS.equals(storeListBean.getResult())) {
                        if(storeListBean.getMap().getStoreList()!=null&&storeListBean.getMap().getStoreList().size()!=0){
                            empty.setVisibility(View.GONE);
                            for (int i = 0; i < storeListBean.getMap().getStoreList().size(); i++) {
//                                    Log.e("距离：",longitude+"--"+latitude+"--"+Double.parseDouble(storeListBean.getMap().getStoreList().get(i).getLongitude())+"--"+Double.parseDouble(storeListBean.getMap().getStoreList().get(i).getLatitude()));
                                storeListBean.getMap().getStoreList().get(i).setDistance(GetDistance(longitude, latitude, Double.parseDouble(storeListBean.getMap().getStoreList().get(i).getLongitude()), Double.parseDouble(storeListBean.getMap().getStoreList().get(i).getLatitude())));
                            }
                            Collections.sort(storeListBean.getMap().getStoreList(), new Comparator<StoreListBean.MapData.StoreListData>() {
                                @Override
                                public int compare(StoreListBean.MapData.StoreListData o1, StoreListBean.MapData.StoreListData o2) {
                                    if (Double.parseDouble(o1.getDistance()) > Double.parseDouble(o2.getDistance())) {
                                        return 1;
                                    }
                                    if (Double.parseDouble(o1.getDistance()) == Double.parseDouble(o2.getDistance())) {
                                        return 0;
                                    }
                                    return -1;
                                }
                            });
                            quickAdapter.clear();
                            quickAdapter.addAll(storeListBean.getMap().getStoreList());
                            quickAdapter.notifyDataSetChanged();
                        }else{
                            empty.setVisibility(View.VISIBLE);
                        }

                    } else {
                        empty.setVisibility(View.VISIBLE);
                        showToast(storeListBean.getMsg());
                    }
                    swiperefresh.setRefreshing(false);
                    mLocationClient.stop();
                    dismissDialog();
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dismissDialog();
                    empty.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    public String GetDistance(double long1, double lat1, double long2, double lat2) {
        DecimalFormat df = new DecimalFormat("######0.00");
        double a, b, d, sa2, sb2;
        lat1 = rad(lat1);
        lat2 = rad(lat2);
        a = lat1 - lat2;
        b = rad(long1 - long2);

        sa2 = Math.sin(a / 2.0);
        sb2 = Math.sin(b / 2.0);
        d = 2 * EARTH_RADIUS
                * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1)
                * Math.cos(lat2) * sb2 * sb2));
        return df.format(d);
    }

    private static final double EARTH_RADIUS = 6378.137;

    private double rad(double d) {
        return d * Math.PI / 180.0;
    }

}
